<?php

namespace App\Http\Controllers;

use App\Http\Services\CategoryService;
use App\Providers\MailSmtp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Providers\MyJwt;
use App\Http\Services\UserService;
use Mockery\CountValidator\Exception;

class DefaultController extends Controller
{

    public function index()
    {
        return view('default.login', ['include' => 'welcome']);
    }

    public function welcome()
    {
        return view('default.welcome');
    }

    public function login()
    {
        return view('default.login');
    }

    public function register()
    {
        return view('default.register');
    }

    public function forget()
    {
        return view('default.forget');
    }

    public function categories(Request $request)
    {
        $this->sendGet(function() use($request){
            $data = CategoryService::categories();
            $this->sendJson($data);
        });
    }

    public function signIn(Request $request)
    {
        $this->sendPost(function() use ($request) {
            $params = $request->get('params');
            if (!array_key_exists('username', $params) ||
                !array_key_exists('password', $params)) {
                $this->sendJson([], 4032, '参数错误');
            }
            $username = $params['username'];
            $password = $params['password'];
            $data = UserService::getByUsernameAndPassword($username, md5($password));
            if ($data) {
                $tomorrow = strtotime(date('Y-m-d', (time()+86400)));
                $jwt = new MyJwt();
                $jwt->payload['uid'] = $data['id'];
                $jwt->payload['role'] = $data['role'];
                $jwt->payload['timeout'] = $tomorrow;

                $cacheKey = sprintf('fc:login:uid:%d', $data['id']);
                Redis::setex($cacheKey, 86400, $tomorrow);
                $data['_token'] = $jwt->encode($jwt->payload, MyJwt::ENCODE_KEY, $jwt->header['alg']);
            }
           $this->sendJson($data);
        });
    }

    public function signUp(Request $request)
    {
        $this->sendPost(function() use ($request) {
            $params = $request->get('params');
            if (!array_key_exists('username', $params) ||
                !array_key_exists('password', $params) ||
                !array_key_exists('re_password', $params) ||
                !array_key_exists('mobile', $params) ||
                !array_key_exists('email', $params)) {
                $this->sendJson([], 4032, '参数错误');
            }
            $option = [
                'username' => $params['username'],
                'password' => md5($params['password']),
                're_password' => md5($params['re_password']),
                'mobile' => $params['mobile'],
                'email' => $params['email']
            ];
            try {
                $data = UserService::register($option);
                if ($data) {
                    $tomorrow = strtotime(date('Y-m-d', (time()+86400)));
                    $jwt = new MyJwt();
                    $jwt->payload['uid'] = $data['id'];
                    $jwt->payload['role'] = $data['role'];
                    $jwt->payload['timeout'] = $tomorrow;

                    $cacheKey = sprintf('fc:login:uid:%d', $data['id']);
                    Redis::setex($cacheKey, 86400, $tomorrow);
                    $data['_token'] = $jwt->encode($jwt->payload, MyJwt::ENCODE_KEY, $jwt->header['alg']);
                }
                $this->sendJson($data);
            } catch (\Exception $e) {
                $this->sendJson([], $e->getCode(), $e->getMessage());
            }
        });
    }

    public function sendEmail(Request $request)
    {
        $this->sendPost(function() use ($request) {
            $params = $request->get('params');
            $user = UserService::getByUsernameAndEmail($params['username'], $params['email']);
            if (empty($user)) {
                $this->sendJson([], 4032, '用户名或邮箱错误');
            }
            try {
                $newPass = $this->getRandomPass();
                $data = [
                    'id' => $user['id'],
                    'password' => md5($newPass)
                ];
                UserService::save($data);
                $result = MailSmtp::send($params['email'], '新密码', "您的新密码为【{$newPass}】,请及时使用新密码登录,并更新您的密码.请注意保密,不要向他人泄露.");
                $this->sendJson([], $result['status'], $result['message']);
            } catch (Exception $e) {
                $this->sendJson([], $e->getCode(), $e->getMessage());
            }
        });
    }

    private function getRandomPass()
    {
        $seed = ['2', '3', '4', '5', '6', '7', '8', '9', 'a', 'c', 'd', 'e', 'f', 'h', 'k', 'm', 't', 'w', 'y'];
        $rand = '';
        for ($i = 0; $i < 6; $i ++) {
            $key = mt_rand(0, 18);
            $rand .= $seed[$key];
        }
        return $rand;
    }
}
